/**
 * 
 */
package info.niwota.commons.web;

import info.niwota.commons.Debug;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;

import org.json.JSONObject;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class ContentHelper {

	private static final String TAG = "ContentHelper";
	
	private static final int BUFSIZE = 1024;

	private ContentHelper() {
	}

	public static String encodeURIComponent(String s) {
		try {
			return URLEncoder.encode(s, "UTF-8");
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return s;
	}

	/**
	 * content://info.niwota.web/path
	 * 
	 * @param path
	 * @return
	 */
	public static Uri buildUri(String path) {
		Uri uri = Uri.parse("content://info.niwota.web" + path);
		return uri;
	}

	public static JsonObject readObject(File file) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(file), BUFSIZE);
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} finally {
			close(br);
		}
		String s = sb.toString();
		JsonObject jo = new JsonObject(s);
		return jo;
	}
	
	public static void saveObject(JSONObject json, File file) throws Exception {
		BufferedWriter out = null;
		try {
			if (!file.exists()) {
				file.getParentFile().mkdirs();
			}
			out = new BufferedWriter(new FileWriter(file), BUFSIZE);
			out.write(json.toString());
		} finally {
			close(out);
		}
	}

	public static String getContent(Context ctx, Uri uri, boolean check) throws Exception {
		String c = getContent(ctx, uri);
		if (check) {
			checkStatus(ctx, c);
		}
		return c;
	}
	
	public static String getContent(Context ctx, Uri uri) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "getContent uri: " + uri);
		}
		InputStream is = ctx.getContentResolver().openInputStream(uri);
		BufferedReader br = new BufferedReader(new InputStreamReader(is), 1024);
		StringBuilder sb = new StringBuilder();
		String line;
		// LF discarded, not a problem for json or html content
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (br != null) {
				br.close();
			}
		}
		return sb.toString();
	}

	public static void saveContent(Context ctx, Uri uri, File file)
			throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "saveContent uri: " + uri);
		}
		InputStream is = null;
		OutputStream os = null;
		try {
			is = ctx.getContentResolver().openInputStream(uri);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
			}
			os = new FileOutputStream(file);
			copy(is, os);
		} finally {
			close(is);
			close(os);
		}
	}
	
	private static void close(Closeable c) throws IOException {
		if (c != null) {
			c.close();
		}
	}

	private static void copy(InputStream is, OutputStream os)
			throws IOException {
		byte[] buf = new byte[1024];
		while (true) {
			int read = is.read(buf);
			if (read == -1) {
				break;
			}
			if (read > 0) {
				os.write(buf, 0, read);
			}
		}
		os.flush();
	}
	
	public static void checkStatus(Context ctx, String c) throws Exception {
		if (c.startsWith("STATUS-5") || c.startsWith("STATUS-4")) {
			throw new Exception(c);
		}	
	}
}
